<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Auth extends MY_Controller
{
	public function __construct()
	{
		parent::__construct();
		$this->layout_view = 'application_no_side_bar';
		$this->load->model('M_users');
		$this->load->library(array('form_validation','token'));
		$this->load->helper(array('url','form'));
		
		if($this->session->userdata('logged_in') == TRUE AND strtolower($this->uri->segment(2)) !== 'logout')
		{
			redirect($this->session->userdata('userType'));
		}
	}
	
	public function index()
	{
		redirect('auth/login');
	}
	
	private function _captcha()
	{
		$this->load->helper('captcha');
		$system_counted_hash = bin2hex(mcrypt_create_iv(32, MCRYPT_DEV_URANDOM));
		$word = substr(md5($system_counted_hash),4,mt_rand(3,5));
		$vals = array(
			'word'	 => $word,
			'img_path'	 => './captcha/',
			'img_url'	 => base_url().'auth/captcha',
			'font_path'	 => './assets/_fonts/4.ttf',
			'img_width'	 => '150',
			'img_height' => 48,
			'expiration' => 7200
			);
		
		$cap = create_captcha($vals);
		$image['word'] = $cap['word'];
		$image['image'] ='<image src="'.base_url().'captcha/'.$cap['time'].'.jpg" class="captcha"/>';
		$image['link'] = './captcha/'.$cap['time'].'.jpg';

		return (object)$image;
	}

	/*12-6-12 Logs the user in the system*/
	function login()
	{
		$this->form_validation->set_error_delimiters('<span class="error_message">', '</span>');
		$this->view_data = $this->session->flashdata('logincred');
		$this->token->set_token();
		$this->layout_view = 'login';
		$captcha = $this->_captcha(); //generate captcha
		$this->session->set_flashdata('image_url',$captcha->link);
		$this->load->library('form_validation');
		$this->view_data['system_message'] = $this->_msg();
		$this->view_data['form_token'] = $this->token->get_token();
		$this->view_data['captcha_image'] = $captcha->image;

		$this->view_data['months'] = ['-- Select --','January','February','March','April','May','June','July','August','September','October','November','December'];

		if($this->input->post('login_student'))
		{
			$post = $this->input->post();
			$this->form_validation->set_rules('username[month]', 'username[month]', 'required|trim|htmlspecialchars|datechecker');
			$this->form_validation->set_rules('username[day]', 'username[day]', 'required|trim|htmlspecialchars');
			$this->form_validation->set_rules('username[year]', 'username[year]', 'required|trim|htmlspecialchars');
			$this->form_validation->set_rules('studentpassword', 'password', 'required|trim|htmlspecialchars');
			$this->form_validation->set_rules('lastname', 'password', 'required|trim|htmlspecialchars');
			$this->form_validation->set_rules('form_input_token', 'Form Token', 'trim|htmlspecialchars');

			//get captcha link from session
			$captcha_image_link = $this->session->flashdata('image_url');
			

			if($this->token->validate_token($this->input->post('form_input_token')))
			{
				if($this->form_validation->run() !== FALSE)
				{
					//hash the word
					$captcha_word = strtolower($this->session->userdata('word'));
					$sent_captcha_text = strtolower($this->input->post('captcha_text'));
				
					// pd($captcha_word,$sent_captcha_text);
				
					if($captcha_word == $sent_captcha_text)
					{
						if($this->M_users->verify_user($this->input->post()))
						{
							$this->session->set_userdata('word',''); //destroy captcha from session
							@unlink($captcha_image_link);//delete captcha image from file
							$this->_msg('s','Welcome to student Portal','student');
						}else
						{
							$this->session->set_flashdata('logincred',$post);
							$this->token->destroy_token();//destroy token
							$this->session->set_userdata('word','');//destroy captcha from session
							$message = '<div class="alert alert-danger">Invalid username/password Combination.</div>';
							$this->_msg('x',$message,'auth/login/');
						}
					}else{
						$this->session->set_flashdata('logincred',$post);
						$this->token->destroy_token();
						$this->session->set_userdata('word','');
						@unlink($captcha_image_link);
						$message = '<div class="alert alert-danger">Invalid CAPTCHA Entered.</div>';
						$this->_msg('x',$message,'auth/login/');
					}
				}else{
					$this->view_data['system_message'] = validation_errors();
				}
			}else{
				$this->token->destroy_token();
				$this->session->set_userdata('word','');
				@unlink($captcha_image_link);
				$message = '<div class="alert alert-danger">Invalid Form Submit detected</div>';
				$this->_msg(FALSE,$message,'auth/login/');
			}
		}elseif($this->input->post('login_parent'))
		{
			$this->form_validation->set_rules('parent_username', 'username', 'required|trim|htmlspecialchars');
			$this->form_validation->set_rules('parent_password', 'password', 'required|trim|htmlspecialchars');
			$this->form_validation->set_rules('form_input_token', 'Form Token', 'trim|htmlspecialchars');

			//get captcha link from session
			$captcha_image_link = $this->session->flashdata('image_url');
			
			// pd($this->input->post());
			if($this->token->validate_token($this->input->post('form_input_token')))
			{
				if($this->form_validation->run() !== FALSE)
				{
					//hash the word
					$captcha_word = strtolower($this->session->userdata('word'));
					$sent_captcha_text = strtolower($this->input->post('captcha_text'));
				
					// pd($captcha_word,$sent_captcha_text);
				
					if($captcha_word == $sent_captcha_text)
					{
						$validation_result = $this->M_users->verify_parent($this->input->post());
						if($validation_result->status === true)
						{
							$this->session->set_userdata('word',''); //destroy captcha from session
							@unlink($captcha_image_link);//delete captcha image from file
							$this->_msg('s',$validation_result->log,'guardian');
						}else
						{
							$this->token->destroy_token();//destroy token
							$this->session->set_userdata('word','');//destroy captcha from session
							$message = '<div class="alert alert-danger">'.$validation_result->log.'</div>';
							$this->_msg('x',$message,'auth/login#parent');
						}
					}else{
						$this->token->destroy_token();
						$this->session->set_userdata('word','');
						@unlink($captcha_image_link);
						$message = '<div class="alert alert-danger">Invalid CAPTCHA Entered.</div>';
						$this->_msg('x',$message,'auth/login#parent');
					}
				}else{
					$this->view_data['system_message'] = validation_errors();
				}
			}else{
				$this->token->destroy_token();
				$this->session->set_userdata('word','');
				@unlink($captcha_image_link);
				$message = '<div class="alert alert-danger">Invalid Form Submit detected</div>';
				$this->_msg(FALSE,$message,'auth/login/#parent');
			}
		}else{
			$this->session->set_userdata('word',$captcha->word);
		}
	}

  function logout($add = '')
  {
		$usertype = $this->session->userdata('userType');
		$message = $this->_msg();
		
		$userdata = array(
			'userid' => '',
			'username' => '',
			'userType' => '',
			'e_f_name' => '',
			'e_l_name' => '',
			'e_m_name' => '',
			'logged_in' => FALSE
		);
		
		$this->session->set_userdata($userdata);

		if($message)
		{
			$this->_msg('s',$message,'auth/login#'.$add);
		}else{
			$message = '<div class="alert alert-info">You Are now logged out</div>';
			$this->_msg('n',$message,'auth/login#'.$add);
		}
    }

    /**
     * Forgot Password
     * @param usertype string
     * Sylver : 8/14/2014
     */
    public function forgot_password($usertype = false)
    {
    	if($usertype === false){ show_404(); }
    	if($usertype === "student" || $usertype === "parent"){
    		// $this->session->set_userdata('word','');
    		$this->form_validation->set_error_delimiters('<div class="alert alert-danger">', '</div>');
			$this->token->set_token();
			$this->layout_view = 'login';
			$captcha = $this->_captcha(); //generate captcha
			$this->session->set_flashdata('image_url',$captcha->link);

			$this->load->library('form_validation');
			$this->view_data['system_message'] = $this->_msg();
			$this->view_data['form_token'] = $this->token->get_token();
			$this->view_data['captcha_image'] = $captcha->image;
			$this->view_data['usertype'] = $usertype;

			if($this->input->post('submit_forgot_password')){

				$this->form_validation->set_rules('email', 'email', 'required|trim|htmlspecialchars|email');

				//get captcha link from session
				$captcha_image_link = $this->session->flashdata('image_url');

				if($this->token->validate_token($this->input->post('form_input_token')))
				{

					if($this->form_validation->run() !== FALSE)
					{
						$captcha_word = strtolower($this->session->userdata('word'));
						$sent_captcha_text = strtolower($this->input->post('captcha_text'));
					
						if($captcha_word == $sent_captcha_text)
						{
							$email = $this->input->post('email');
							$validation_result = $this->M_users->verify_user_email($email, $usertype);

							if($validation_result->status){

								/* SEND THEM EMAIL */
								if($validation_result->data){
									foreach ($validation_result->data as $key => $value) {
										$this->_send_forgot_password_to_email($value, $usertype);
									}

									$this->token->destroy_token();//destroy token
									$this->session->set_userdata('word','');//destroy captcha from session
									$message = '<div class="alert alert-success">Your password has been sent to your email.</div>';
									$this->_msg('s',$message,current_url());
								}
							}else{

								$this->token->destroy_token();
								$this->session->set_userdata('word','');
								@unlink($captcha_image_link);
								$message = '<div class="alert alert-danger">The email address you have entered was invalid.</div>';
								$this->_msg('x',$message,current_url());
							}
							
						}else{
							$this->token->destroy_token();
							$this->session->set_userdata('word','');
							@unlink($captcha_image_link);
							$message = '<div class="alert alert-danger">Invalid CAPTCHA Entered.</div>';
							$this->_msg('x',$message,current_url());
						}
					}else{
						// pd(validation_errors());
						$this->token->destroy_token();
						$this->session->set_userdata('word','');
						@unlink($captcha_image_link);
						$message = validation_errors();
						$this->_msg('x',$message,current_url());
					}
				}else{

					$this->token->destroy_token();
					$this->session->set_userdata('word','');
					@unlink($captcha_image_link);
					$message = '<div class="alert alert-danger">Invalid Form Submit detected</div>';
					$this->_msg(FALSE,$message,current_url());
				}
			}else{
				$this->session->set_userdata('word',$captcha->word);
			}
    	}else{
    		show_404();
    	}
  }

  private function _send_forgot_password_to_email($val, $usertype)
  {
    $this->load->library('email');
		$this->email->initialize(array( 
		   'mailtype' => 'html', 
		));

		$usertype = $usertype == "parent" ? "guardian" : $usertype;
		$school_name = ucwords($this->school_name);
		$school_name_title = $this->_accronymizer($this->school_name).'@DONOTREPLY.com';
		
		if($this->school_tag_name == FALSE)
		{
			$tagname = 'part of '.$school_name;
		}else{
			$tagname = 'a '.strtoupper($this->school_tag_name);
		}
		
		$this->load->model('M_enrollees');
		$user_password = $this->M_enrollees->get_raw_password($val->id, $usertype);

		if($user_password){

			$data['school_name'] = $school_name;
			$data['acc'] = $school_name_title;
			$data['link'] = $this->student_link;
			$data['tagname'] = $tagname;
			$data['username'] = $val->username;
			$data['password'] = $user_password;
			
			if($usertype === "student"){
				$data['name'] = $val->fullname;
				$message = $this->load->view('email_templates/student_forgot_password',$data,TRUE);
			}else{
				$message = $this->load->view('email_templates/parent_forgot_password',$data,TRUE);
			}

			$this->email->from($school_name_title,$school_name);
			$this->email->to($val->email);
			$this->email->subject('Requested Login Details.');
			$this->email->message($message);
			$this->email->send();	
			
			return true;

		}else{

		}	
  }
}